package com.hdyg.csc.activity;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.hdyg.csc.R;
import com.hdyg.csc.activity.common.BaseActivity;
import com.hdyg.csc.app.MvpApplication;
import com.hdyg.csc.mvp.base.BasePresenter;
import com.hdyg.csc.mvp.base.BaseUrl;
import com.hdyg.csc.ui.CustomProgressDialog;
import com.hdyg.csc.ui.MyWebView;
import com.hdyg.csc.util.AlertDialogUtil;
import butterknife.BindView;
import okhttp3.Cookie;

/**
 * Created by CWJ on 2017/12/20.
 * web 界面
 */

public class WebActivity extends BaseActivity {


    @BindView(R.id.webView)
    MyWebView mWebView;

    private String URL;//传递的URL
    private CustomProgressDialog progressDialog;
    private boolean isCertain = false;
    private final int FILECHOOSER_RESULTCODE = 0x0001;//文件选择回调
    private final static int SCAN_QRCODE_REQUEST_CODE = 0x1100;//扫描回调
    private ValueCallback<Uri> mUploadMessage;
    private ValueCallback<Uri[]> mUploadCallbackAboveL;
    private String desCpt, failUrl;
    /** 视频全屏参数 */
    protected static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
    private View customView;
    private FrameLayout fullscreenContainer;
    private WebChromeClient.CustomViewCallback customViewCallback;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_web_view);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_browser;
    }

    @Override
    protected void initView() {

        URL = getIntent().getStringExtra("url");
        initWebView();
//        synCookies(URL);//同步cookie
        mWebView.loadUrl(URL);

    }

    /**
     * 同步一下cookie
     */
    public void synCookies(String url) {
        Cookie sessionCookie = MvpApplication.cookie;    //这里的cookie就是上面保存的cookie
        CookieSyncManager.createInstance(this);
        CookieManager cookieManager = CookieManager.getInstance();
        if (sessionCookie != null) {
            cookieManager.removeSessionCookie();
            String cookieString = sessionCookie.name() + "=" + sessionCookie.value() + "; domain=" + sessionCookie.domain();
            cookieManager.setCookie(url, cookieString);
            Log.d("czb", cookieString);
            CookieSyncManager.getInstance().sync();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() {
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.d("czb", "url=====" + url);
                if (url.startsWith("http:") || url.startsWith("https:") || url.startsWith("HTTP:") || url.startsWith("HTTPS:")) {
                    view.loadUrl(url);
                    return false;
                } else if (url.contains("tel:")) {
                    //拨打电话
                    Uri uri = Uri.parse(url);
                    Intent mIntent = new Intent(Intent.ACTION_DIAL, uri);
                    if (ActivityCompat.checkSelfPermission(WebActivity.this, android.Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
                        startActivity(mIntent);
                        return true;
                    } else {
                        ActivityCompat.requestPermissions(WebActivity.this, new String[]{android.Manifest.permission.CALL_PHONE}, 1);
                        return true;
                    }
                } else if (url.startsWith("weixin://") || url.startsWith("alipays://") || url.startsWith("intent://") || url.startsWith("mqqapi://")) {
                    try {
                        mContext.startActivity(new Intent("android.intent.action.VIEW", Uri.parse(url)));
                    } catch (Exception e) {
                        if (url.startsWith("alipays://")){
                            AlertDialogUtil.getInstance().showDialog(mContext, "温馨提示", "未检测到支付宝客户端，请请安装后重试!", new AlertDialogUtil.OnClickYesListener() {
                                @Override
                                public void onClickYes() {
                                    // 点击按钮所调用的方法
                                    Uri alipayUrl = Uri.parse("https://d.alipay.com");
                                    mContext.startActivity(new Intent("android.intent.action.VIEW", alipayUrl));
                                }
                            }, false);
                        }
                        return false;
                    }
                    return true;
                }else {
//                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
//                    startActivity(intent);
                    return true;
                }
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                // TODO Auto-generated method stub
                super.onPageStarted(view, url, favicon);
//                progressDialog.show();
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                // TODO Auto-generated method stub
                super.onPageFinished(view, url);
//                progressDialog.hide();
                view.loadUrl("javascript:chaoS('" + desCpt + "','" + failUrl + "')");
            }

            // TODO: 2018/4/23 加载出错时显示
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
//                progressDialog.hide();
                view.loadUrl(BaseUrl.NET_FAIL_URL);
                desCpt = description;
                failUrl = failingUrl;
            }
        });
        mWebView.setWebChromeClient(new WebChromeClient() {

            @Override
            public boolean onJsConfirm(WebView arg0, String arg1, String arg2,
                                       JsResult arg3) {
                return super.onJsConfirm(arg0, arg1, arg2, arg3);
            }

            //
            /*** 视频播放相关的方法 **/
            @Override
            public View getVideoLoadingProgressView() {
                FrameLayout frameLayout = new FrameLayout(mContext);
                frameLayout.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                return frameLayout;
            }

            @Override
            public void onShowCustomView(View view, CustomViewCallback callback) {
                showCustomView(view, callback);
            }

            @Override
            public void onHideCustomView() {
                hideCustomView();
            }

            // ======================== 自定义的window alert ============================
            @Override
            public boolean onJsAlert(WebView arg0, String arg1, String arg2,
                                     final JsResult arg3) {
                /**
                 * 这里写入你自定义的window alert
                 */
//                return super.onJsAlert(null, arg1, arg2, arg3);
                View view = LayoutInflater.from(mContext).inflate(R.layout.window_alert, null);
                TextView title = (TextView) view.findViewById(R.id.title);
                TextView content = (TextView) view.findViewById(R.id.content);
                TextView certain = (TextView) view.findViewById(R.id.certain);
                // 实例化 AlertDialog
                final AlertDialog alertDialog = new AlertDialog.Builder(mContext).create();
                // 获取 AlertDialog 的窗体
                Window window = alertDialog.getWindow();
                // 设置背景透明
                window.setBackgroundDrawableResource(android.R.color.transparent);
                // 标题
                title.setText("温馨提示");
                // 内容
                content.setText(arg2);
                // 设置点击系统返回可以关闭
                alertDialog.setCancelable(true);
                // 显示
                alertDialog.show();
                // 加载布局，必须在 show 之后
                window.setContentView(view);
                // 点击事件
                certain.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        isCertain = true;
                        alertDialog.dismiss();
                    }
                });
                alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        if (isCertain) {
                            arg3.confirm();
                        } else {
                            arg3.cancel();
                        }
                    }
                });

                return true;
            }
            // =============================== 弹窗 =======================================

            // =============================== 文件上传 ====================================


            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                super.onShowFileChooser(webView, filePathCallback, fileChooserParams);
                mUploadCallbackAboveL = filePathCallback;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                WebActivity.this.startActivityForResult(
                        Intent.createChooser(i, "File Browser"),
                        FILECHOOSER_RESULTCODE);
                return true;
            }

            /**
             * 获取标题的方法
             * @param view
             * @param title
             */
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
            }

            // ======================================================================

        });

    }
    /** 视频播放全屏 **/
    private void showCustomView(View view, WebChromeClient.CustomViewCallback callback) {
        // if a view already exists then immediately terminate the new one
        if (customView != null) {
            callback.onCustomViewHidden();
            return;
        }

        this.getWindow().getDecorView();
        FrameLayout decor = (FrameLayout) getWindow().getDecorView();
        fullscreenContainer = new FullscreenHolder(mContext);
        fullscreenContainer.addView(view, COVER_SCREEN_PARAMS);
        decor.addView(fullscreenContainer, COVER_SCREEN_PARAMS);
        customView = view;
        setStatusBarVisibility(false);
        customViewCallback = callback;
    }
    private void setStatusBarVisibility(boolean visible) {
        int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
        getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }
    /** 全屏容器界面 */
    static class FullscreenHolder extends FrameLayout {

        public FullscreenHolder(Context ctx) {
            super(ctx);
            setBackgroundColor(ctx.getResources().getColor(android.R.color.black));
        }

        @Override
        public boolean onTouchEvent(MotionEvent evt) {
            return true;
        }
    }
    /** 隐藏视频全屏 */
    private void hideCustomView() {
        if (customView == null) {
            return;
        }

        setStatusBarVisibility(true);
        FrameLayout decor = (FrameLayout) getWindow().getDecorView();
        decor.removeView(fullscreenContainer);
        fullscreenContainer = null;
        customView = null;
        customViewCallback.onCustomViewHidden();
        mWebView.setVisibility(View.VISIBLE);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_CANCELED) {
            if (mUploadCallbackAboveL != null) {
                mUploadCallbackAboveL.onReceiveValue(null);
                mUploadCallbackAboveL = null;
            }
            return;
        }
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case FILECHOOSER_RESULTCODE://文件上传
                if (null == mUploadMessage && null == mUploadCallbackAboveL) return;
                Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
                if (mUploadCallbackAboveL != null) {
                    onActivityResultAboveL(requestCode, resultCode, data);
                } else if (mUploadMessage != null) {
                    mUploadMessage.onReceiveValue(result);
                    mUploadMessage = null;
                }
                break;
        }
    }

    //    文件上传
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {
        if (requestCode != FILECHOOSER_RESULTCODE
                || mUploadCallbackAboveL == null) {
            return;
        }
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (data == null) {
            } else {
                String dataString = data.getDataString();
                ClipData clipData = data.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }
                if (dataString != null)
                    results = new Uri[]{Uri.parse(dataString)};
            }
        }
        mUploadCallbackAboveL.onReceiveValue(results);
        mUploadCallbackAboveL = null;
        return;
    }

    @Override
    protected void initData() {

    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected CustomProgressDialog createProgress() {
        progressDialog = new CustomProgressDialog(mContext, R.style.loading_dialog);
        return progressDialog;
    }

    /**
     * 系统返回键回退处理
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
            mWebView.goBack();
            return true;
        } else {
            this.finish();
            return true;
        }
    }

}
